package com.horsen.common.util;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一返回结果
 *
 * @author Horsen
 */
@ApiModel("统一返回结果")
@Data
@Accessors(chain = true)
public class R {
    @ApiModelProperty("是否成功")
    private Boolean success;

    @ApiModelProperty("返回码")
    private Integer code;

    @ApiModelProperty("返回消息")
    private String message;

    @ApiModelProperty("返回数据")
    private Map<String, Object> data = new HashMap<>();

    public R() {
    }

    /**
     * 返回成功结果
     *
     * @return 统一返回结果实例
     */
    public static R ok() {
        return new R()
                .setSuccess(ResultCodeEnum.SUCCESS.getSuccess())
                .setCode(ResultCodeEnum.SUCCESS.getCode())
                .setMessage(ResultCodeEnum.SUCCESS.getMessage());
    }

    /**
     * 返回成功结果
     *
     * @param msg 自定义消息
     * @return 统一返回结果实例
     */
    public static R ok(String msg) {
        return new R()
                .setSuccess(ResultCodeEnum.SUCCESS.getSuccess())
                .setCode(ResultCodeEnum.SUCCESS.getCode())
                .setMessage(msg);
    }

    /**
     * 返回失败结果 用于处理RuntimeException
     *
     * @param code    状态码
     * @param message 消息
     * @return 统一返回结果实例
     */
    public static R error(Integer code, String message) {
        return new R()
                .setSuccess(false)
                .setCode(code)
                .setMessage(message);
    }

    /**
     * 返回失败结果
     *
     * @return 统一返回结果实例
     */
    public static R error() {
        return new R()
                .setSuccess(ResultCodeEnum.UNKNOWN_REASON.getSuccess())
                .setCode(ResultCodeEnum.UNKNOWN_REASON.getCode())
                .setMessage(ResultCodeEnum.UNKNOWN_REASON.getMessage());
    }

    /**
     * 返回失败结果
     *
     * @param msg 自定义消息
     * @return 统一返回结果实例
     */
    public static R error(String msg) {
        return new R()
                .setSuccess(ResultCodeEnum.UNKNOWN_REASON.getSuccess())
                .setCode(ResultCodeEnum.UNKNOWN_REASON.getCode())
                .setMessage(msg);
    }

    /**
     * 返回自定义结果
     *
     * @param resultCodeEnum 返回码枚举对象
     * @return 统一返回结果实例
     */
    public static R setResult(ResultCodeEnum resultCodeEnum) {
        return new R()
                .setSuccess(resultCodeEnum.getSuccess())
                .setCode(resultCodeEnum.getCode())
                .setMessage(resultCodeEnum.getMessage());
    }

    /**
     * 为data赋值
     *
     * @param key   键
     * @param value 值
     * @return 统一返回结果实例
     */
    public R setData(String key, Object value) {
        this.data.put(key, value);
        return this;
    }
}
